package com.example.comparator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class comparator1 {

    public static void main(String[] args) {

//        通过实现Comparator接口来进行排序，代码相对较复杂
//        Collections.sort(models,new Comparator<String>(){
//            @Override
//            public int compare (String o1, String o2) {
//                return o1.compareTo(o2);
//            }
//            });

        List<Model> models = new ArrayList<>();
        Model model1 = new Model();
        model1.setAge(300);
        model1.setName("a");
        models.add(model1);

        Model model2 = new Model();
        model2.setAge(500);
        model2.setName("c");
        models.add(model2);

        Model model4 = new Model();
        model4.setAge(500);
        model4.setName("d");
        models.add(model4);

        Model model3 = new Model();
        model3.setAge(100);
        model3.setName("b");
        models.add(model3);

        System.out.println("----排序前-----");
        //排序前
        for (Model contract : models){
            System.out.println(contract.getName() + " " + contract.getAge());
        }

        System.out.println("-----排序后，根据age排序-----");
        Collections.sort(models, Comparator.comparing(Model::getAge));
        //排序后
        for (Model model: models){
            System.out.println(model.getName() + " " + model.getAge());
        }

        System.out.println("-----排序后，根据age排倒序-----");
        Collections.sort(models,Comparator.comparing(Model::getAge).reversed());

        for (Model model : models) {
            System.out.println(model.getName() + " " + model.getAge());
        }

        System.out.println("-----排序后，根据name排序-----");

        Collections.sort(models,Comparator.comparing(Model::getName));

        // 排序后
        for (Model model : models) {
            System.out.println(model.getName() + " " + model.getAge());
        }

        System.out.println("-----使用流进行排序 排序后，根据name排序-----");

        List<Model> collect = models.stream().sorted(Comparator.comparing(Model::getAge).reversed()).collect(Collectors.toList());
         models.stream().sorted(Comparator.comparing(Model::getAge).reversed()).collect(Collectors.toList()).forEach(System.out::println);

         Collections.sort(models,Comparator.comparing(Model::getAge).thenComparing(Model::getName).reversed());
         for (Model model : models){
             System.out.println(model.getName() + " " + model.getAge());
         }
        /**
         * .reversed() 倒序  放的位置不同  影响 一次排序 二次排序 结果
         * .forEach(System.out::println)  打印
         *.thenComparing(Model::getName) 在程序里代表，如果年龄相同就比较 姓名
         */
        //使用流进行排序
        for (Model model : collect) {
            System.out.println(model.getName() + " " + model.getAge());
        }
    }
}